package cn.tedu.myweb.service.impl;

import cn.tedu.myweb.exception.ServiceException;
import cn.tedu.myweb.mapper.ChatsMapper;
import cn.tedu.myweb.mapper.UserMapper;
import cn.tedu.myweb.model.Chats;
import cn.tedu.myweb.model.User;
import cn.tedu.myweb.service.IChatsService;
import cn.tedu.myweb.vo.ChatVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ChatsServiceImpl extends ServiceImpl<ChatsMapper, Chats> implements IChatsService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    ChatsMapper chatsMapper;


    @Override
    public List<Chats> getChatList(String friendName, int master,int userId) {
        List<Chats> chats;
        if(master==userId){
            chats = chatsMapper
                    .getFriendChatHistory1(friendName,userId);
        }else{
            chats = chatsMapper.getFriendChatHistory2(friendName,userId);
        }
        return chats;
    }

    @Override
    public void saveChatHistory(ChatVo chatVo, String username) {
        User user = userMapper.findUserByUsername(username);
        Chats chat = new Chats()
                .setChat(chatVo.getChat())
                .setCreateTime(LocalDateTime.now())
                .setRoomId(chatVo.getRoomId())
                .setUserId(user.getId())
                .setMasterId(chatVo.getMasterId());
        int num = chatsMapper.insert(chat);
        if(num != 1){
            throw new ServiceException("数据库忙！");
        }
    }
}
